<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区 -->
    <el-card style="margin-top: 15px">
      <!-- 消息提示 -->
      <el-alert title="添加商品" type="info" show-icon center> </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab 标签页 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTableLeave"
          @tab-click="tabClicked"
        >
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_prince"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_price">
              <el-input type="number" v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_prince"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="GoodsCateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <el-upload
              :action="picUploadRul"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="hearderObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              ref="myQuillEditor"
              v-model="addForm.goods_introduce"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @ready="onEditorReady($event)"
            />
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预处理对话框 -->
    <el-dialog title="图片预览" :visible.sync="preDialogVisible" width="50%">
      <img src=" preViewPath" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      // 表单数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 级联选择器 选中项绑定的值
        goods_cat: [],
        goods_introduce: '',
      },
      // 表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
      },
      // 商品分类数据
      GoodsCateList: [],
      // 级联配置选项
      cateProps: {
        label: 'cate_name',
        value: 'cat_id',
        children: 'children',
      },
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      //  图片上传 后台API地址
      picUploadRul: 'http://127.0.0.1:8888/api/private/v1/upload',
      //  图片上传请求头
      hearderObj: {
        Authorization: Window.sessionStorage.getItem('token'),
      },
      // 上传图片零时路径的数组
      pics: [],
      preViewPath: '',
      preDialogVisible: false,
    }
  },
  created() {
    // this.getGoodsList()
  },
  methods: {
    // 获取分类商品 数据
    async getGoodsList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.GoodsCateList = res.data
    },
    // 级联选中器选中项发生变化，就会触发
    handleChange() {
      // 只允许选中三分类
      if (this.addForm.goods_cat.length !== 3) {
        return (this.addForm.goods_cat = [])
      }
    },
    // 不允许跳过
    beforeTableLeave(activeName, oldAciveName) {
      if (oldAciveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
      // console.log(activeName, old)
    },
    // tab 点击事件
    async tabClicked() {
      // console.log(this.activeIndex)
      // 如果点击跳转到 商品参数项
      if (this.activeIndex === '1') {
        // 访问动态参数面板
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数失败')
        }
        res.data.forEach((item) => {
          // 字符串=>数组
          item.attr_vals = item.attr_vals =
            length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败')
        }
        this.onlyTableData = res.data
      }
      //
    },
    // 处理图片预览效果
    handlePreview(file) {
      this.preViewPath = file.response.data.picUploadRul
      this.preDialogVisible = true
    },
    // 图片移出
    handleRemove(file) {
      //  1 获取将要删除的图片的临时路径
      const filePath = file.response.data.tem_path
      //  2从pics数组中找到这个图片对应的索引值
      const i = this.addForm.pics.findIndex((x) => x.pic === filePath)
      //  3调用数组的splice方法，把图片信息对象，从pics数组中移出
      this.addForm.pics.splice(i, 1)
    },
    // 图片上传成功
    handleSuccess(response) {
      // 1 拼接得到一个图片信息对象
      const picInfo = {
        pic: response.data.tem_path,
      }
      // 将图片信息对象push 到pics数组中
      this.addForm.pics.push(picInfo)
    },
    // 添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 深拷贝 addForm
        const from = _.cloneDeep(this.addForm)
        from.goods_cat = from.goods_cat.join(',')
        // 处理动态参数和静态属性
        this.manyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.addForm.attr.push(newInfo)
        })
        // 静态属性
        this.onlyTableData.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          }
          this.addForm.attr.push(newInfo)
        })
        from.attrs = this.addForm.attrs
        // 发起请求 添加商品
        const { date: res } = await this.$http.post('goods', from)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
      })
    },
  },
  // 计算属性
  computed: {
    // 获取三级分类 商品的ID
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>

<style scoped>
.el-alert {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
</style>
